/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.Layout;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.CommentService;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.user.object.Focus;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.FavouriteService;
import etcore.webapp.grouptalk.user.service.FocusService;
import etcore.webapp.grouptalk.user.service.MemberService;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.StringDisplay;

/**
 * This action validates the request and executes the command of showing the
 * welcome/home page,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class GroupDataAction extends AbstractAction {

	private static final long serialVersionUID = 4370833856302988386L;
	// validate result
	public static final int START = 1;
	public static final String GROUP_MAP = "groupMap";

	public static final String PUBLIC_MSGS = "publicMsgs";
	public static final String HOTTEST_MSGS = "hottestMsgs";
	public static final String GROUP_MSG_COUNT = "groupMsgCount";
	public static final String GROUP_COMMENT_COUNT = "groupCommentCount";

	// utility constants

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return START;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {

		return PageConstants.PAGE_PATH_GROUPDATA;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		Map groupMap = new HashMap();
		Map<String, String> context = (Map<String, String>) request
				.getAttribute(Messages.CONTEXT);
		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_MESSAGES))) {
			getLatestMsgs(request, groupMap);
			// getHottestMsgs(request, groupMap, 2);
			getHottestMsgs(request, groupMap, 7);
			getHottestMsgs(request, groupMap, 31);
			//getHottestMsgs(request, groupMap, 365);
			request.setAttribute(GROUP_MAP, groupMap);
		}
		if (!PageConstants.ZERO.equals(context.get(Layout.LEFT))) {
			// getUserActivityDegree(request, 7);
			getUserActivityDegree(request, 31);
			getUserActivityDegree(request, 365);
			getStarsOfUsers(request);
			getStarsOfGroups(request);
		}
		getDirectories(request);

		getActiveGroups(request);

		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_USERS))) {

			getUserBehaviours(request);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void getActiveGroups(HttpServletRequest request) {
		GroupService groupService = new GroupService();
		TopicService topicService = new TopicService();
		MessageService msgService = new MessageService();
		CommentService commentService = new CommentService();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(PageConstants.SESSIONUSER);

		String lang = (String) session.getAttribute(Messages.LANG);
		Map<String, String> context = (Map<String, String>) request
				.getAttribute(Messages.CONTEXT);
		Map<Integer, String> topicMap = new HashMap<Integer, String>();
		int msgCount = 5;
		List<Group> newsGroups = new ArrayList<Group>();
		List<Group> aboutGroups = new ArrayList<Group>();
		List<Group> feedbackGroups = new ArrayList<Group>();
		List<Group> communityGroups = new ArrayList<Group>();

		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_PLATFORM1))) {
			List groups1 = null;
			if (Messages.LANG_LOCAL.equals(lang)) {
				groups1 = groupService
						.findActiveGroupIDs(1, 0, 365, true, 0, 4);
			} else {
				groups1 = groupService.findActiveGroupIDs(1, 0, 365, false, 0,
						4);
			}

			for (Iterator iter = groups1.iterator(); iter.hasNext();) {
				Integer id = (Integer) iter.next();
				Group group = groupService.findById(id);
				long groupMsgCount = msgService.findSizeByGid(group.getId());
				// long todayGroupMsgCount = msgService.findSizeByDaysAndGid(1,
				// group.getId())
				// + commentService.searchSizeByGidAndDays(group.getId(), 1);
				request.setAttribute(group.getId() + GROUP_MSG_COUNT,
						groupMsgCount);
				request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
						commentService.searchSizeByGid(group.getId()));
				// request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
				// commentService.searchSizeByGid(group.getId()));
				newsGroups.add(group);

				List<Topic> topics = topicService.findByProperty(
						PageConstants.GID, new Integer(group.getId()));
				request.setAttribute(group.getId() + PageConstants.TOPICS,
						topics);

				for (Topic topic : topics) {
					topicMap.put(topic.getId(), topic.getName());
				}

				List msgs = msgService.findTopByDaysAndGid(new Integer(2000),
						group.getId(), 0, msgCount);
				request.setAttribute(group.getId() + PageConstants.MSGS, msgs);

			}
			request.setAttribute("activeNewsGroups", newsGroups);
		}
		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_NAV1))) {
			List groups1 = null;
			if (Messages.LANG_LOCAL.equals(lang)) {
				groups1 = groupService
						.findActiveGroupIDs(1, 1, 365, true, 0, 4);
			} else {
				groups1 = groupService.findActiveGroupIDs(1, 1, 365, false, 0,
						4);
			}

			for (Iterator iter = groups1.iterator(); iter.hasNext();) {
				Integer id = (Integer) iter.next();
				Group group = groupService.findById(id);
				long groupMsgCount = msgService.findSizeByGid(group.getId());
				// long todayGroupMsgCount = msgService.findSizeByDaysAndGid(1,
				// group.getId())
				// + commentService.searchSizeByGidAndDays(group.getId(), 1);
				request.setAttribute(group.getId() + GROUP_MSG_COUNT,
						groupMsgCount);
				request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
						commentService.searchSizeByGid(group.getId()));
				// request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
				// commentService.searchSizeByGid(group.getId()));
				aboutGroups.add(group);

				List<Topic> topics = topicService.findByProperty(
						PageConstants.GID, new Integer(group.getId()));
				request.setAttribute(group.getId() + PageConstants.TOPICS,
						topics);

				for (Topic topic : topics) {
					topicMap.put(topic.getId(), topic.getName());
				}

				List msgs = msgService.findTopByDaysAndGid(new Integer(2000),
						group.getId(), 0, msgCount);
				request.setAttribute(group.getId() + PageConstants.MSGS, msgs);

			}
			request.setAttribute("activeAboutGroups", aboutGroups);
		}
		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_PLATFORM2))) {
			List groups2 = null;
			if (Messages.LANG_LOCAL.equals(lang)) {
				groups2 = groupService.findActiveGroupIDs(2, 0, 14, true, 0, 6);
			} else {
				groups2 = groupService
						.findActiveGroupIDs(2, 0, 14, false, 0, 6);
			}
			for (Iterator iter2 = groups2.iterator(); iter2.hasNext();) {
				Integer id = (Integer) iter2.next();
				Group group = groupService.findById(id);
				long groupMsgCount = msgService.findSizeByGid(group.getId());

				request.setAttribute(group.getId() + GROUP_MSG_COUNT,
						groupMsgCount);
				request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
						commentService.searchSizeByGid(group.getId()));
				communityGroups.add(group);
				if (user != null) {
					MemberService memberService = new MemberService();
					Member member = memberService.findByUsernameAndGid(
							user.getUserName(), group.getId());
					if (member != null)
						request.setAttribute("included" + group.getId(), true);
					else
						request.setAttribute("included" + group.getId(), false);
				}
				if (group.getFunc() == 0) {
					List<Topic> topics = topicService.findByProperty(
							PageConstants.GID, new Integer(group.getId()));
					request.setAttribute(group.getId() + PageConstants.TOPICS,
							topics);

					for (Topic topic : topics) {
						topicMap.put(topic.getId(), topic.getName());
					}

					List msgs = msgService.findTopByDaysAndGid(
							new Integer(2000), group.getId(), 0, msgCount);
					request.setAttribute(group.getId() + PageConstants.MSGS,
							msgs);

				}
			}
			request.setAttribute("activeCommunityGroups", communityGroups);
		}
		if (!PageConstants.ZERO.equals(context.get(Layout.MAIN_NAV2))) {
			List groups2 = null;
			if (Messages.LANG_LOCAL.equals(lang)) {
				groups2 = groupService.findActiveGroupIDs(2, 1, 365, true, 0, 4);
			} else {
				groups2 = groupService
						.findActiveGroupIDs(2, 1, 365, false, 0, 4);
			}
			for (Iterator iter2 = groups2.iterator(); iter2.hasNext();) {
				Integer id = (Integer) iter2.next();
				Group group = groupService.findById(id);
				long groupMsgCount = msgService.findSizeByGid(group.getId());

				request.setAttribute(group.getId() + GROUP_MSG_COUNT,
						groupMsgCount);
				request.setAttribute(group.getId() + GROUP_COMMENT_COUNT,
						commentService.searchSizeByGid(group.getId()));
				feedbackGroups.add(group);
				if (user != null) {
					MemberService memberService = new MemberService();
					Member member = memberService.findByUsernameAndGid(
							user.getUserName(), group.getId());
					if (member != null)
						request.setAttribute("included" + group.getId(), true);
					else
						request.setAttribute("included" + group.getId(), false);
				}
				if (group.getFunc() == 0) {
					List<Topic> topics = topicService.findByProperty(
							PageConstants.GID, new Integer(group.getId()));
					request.setAttribute(group.getId() + PageConstants.TOPICS,
							topics);

					for (Topic topic : topics) {
						topicMap.put(topic.getId(), topic.getName());
					}

					List msgs = msgService.findTopByDaysAndGid(
							new Integer(2000), group.getId(), 0, msgCount);
					request.setAttribute(group.getId() + PageConstants.MSGS,
							msgs);

				}
			}
			request.setAttribute("activeFeedbackGroups", feedbackGroups);
		}

		
		request.setAttribute(PageConstants.TOPIC_MAP, topicMap);
	}

	private void getStarsOfGroups(HttpServletRequest request) {
		MemberService memberService = new MemberService();
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);

		@SuppressWarnings("rawtypes")
		List groupStars = null;
		if (Messages.LANG_LOCAL.equals(lang)) {
			groupStars = memberService.findLocalGroupStars(2, 0, 10);

		} else if (Messages.LANG_EN.equals(lang)) {

			groupStars = memberService.findEnglishGroupStars(2, 0, 10);

		} else if (request.getLocale().getLanguage()
				.equals(Config.getProperty(Config.LOCAL_LANG))) {
			groupStars = memberService.findLocalGroupStars(2, 0, 10);

		} else {
			groupStars = memberService.findEnglishGroupStars(2, 0, 10);

		}

		request.setAttribute("groupStars", groupStars);

	}

	private void getDirectories(HttpServletRequest request) {
		DirectoryService directoryService = new DirectoryService();
		List<Directory> directories = directoryService.findByParent(-4);
		if (directories != null) {
			request.setAttribute("directories", directories);
		}

	}
	@SuppressWarnings("rawtypes")
	private void getStarsOfUsers(HttpServletRequest request) {
		FocusService focusService = new FocusService();
		UserService userService = new UserService();

		
		long userSize = userService.findSize();
		List users = userService.findUsers(0, 10);
	
		List userStars = focusService.findUserStars(0, 10);

		request.setAttribute("userStars", userStars);
		request.setAttribute("users", users);
		request.setAttribute("userSize", userSize);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void getLatestMsgs(HttpServletRequest request, Map groupMap) {
		MessageService messageService = new MessageService();
		UserService userService = new UserService();
		List publicMessages = null;
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (Messages.LANG_LOCAL.equals(lang)) {
			publicMessages = messageService.findPublicLocalMessages(0, 20);

		} else if (Messages.LANG_EN.equals(lang)) {

			publicMessages = messageService.findPublicEnglishMessages(0, 20);

		} else if (request.getLocale().getLanguage()
				.equals(Config.getProperty(Config.LOCAL_LANG))) {
			publicMessages = messageService.findPublicLocalMessages(0, 20);

		} else {
			publicMessages = messageService.findPublicEnglishMessages(0, 20);

		}

		GroupService groupService = new GroupService();

		Iterator publicMsgsIterator = publicMessages.iterator();

		while (publicMsgsIterator.hasNext()) {
			Object[] tempm = (Object[]) publicMsgsIterator.next();
			String tempm_source = (String) tempm[9];
			String tempm_stime = (String) tempm[10];
			Integer tempm_id = (Integer) tempm[0];
			String userName = (String) tempm[4];
			String toUserAvatar = (String) request.getAttribute(userName
					+ PageConstants.AVATAR_POSTFIX);
			if (toUserAvatar == null) {
				User toUser = userService.findByUserName(userName);
				if (toUser != null)
					request.setAttribute(userName
							+ PageConstants.AVATAR_POSTFIX, toUser.getAvatar());
			}
			Group group = groupService.findGroupByGmid(tempm_id);
			if (group != null)
				groupMap.put(tempm_id, group);

			if (group.getOpen() == 4) {
				StringBuffer reminderDate = StringDisplay
						.getReminderDateStringBuffer(tempm_source, tempm_stime);
				request.setAttribute(tempm_id + PageConstants.REMINDER_DATE,
						reminderDate.toString());
			}
		}

		request.setAttribute(PUBLIC_MSGS, publicMessages);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void getHottestMsgs(HttpServletRequest request, Map groupMap,
			int days) {
		MessageService messageService = new MessageService();

		List hottestMessages = null;
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (Messages.LANG_LOCAL.equals(lang)) {

			hottestMessages = messageService.findHottestPublicLocalMessages(
					days, 0, 15);

		} else if (Messages.LANG_EN.equals(lang)) {

			hottestMessages = messageService.findHottestPublicEnglishMessages(
					days, 0, 15);

		} else if (request.getLocale().getLanguage()
				.equals(Config.getProperty(Config.LOCAL_LANG))) {

			hottestMessages = messageService.findHottestPublicLocalMessages(
					days, 0, 15);

		} else {

			hottestMessages = messageService.findHottestPublicEnglishMessages(
					days, 0, 15);
		}

		GroupService groupService = new GroupService();

		Iterator hottestMsgsIterator = hottestMessages.iterator();
		while (hottestMsgsIterator.hasNext()) {
			Object[] tempm = (Object[]) hottestMsgsIterator.next();
			Integer tempm_id = (Integer) tempm[0];
			String tempm_source = (String) tempm[9];
			String tempm_stime = (String) tempm[10];
			Group group = groupService.findGroupByGmid(tempm_id);
			if (group != null)
				groupMap.put(tempm_id, group);
			if (group.getOpen() == 4) {
				StringBuffer reminderDate = StringDisplay
						.getReminderDateStringBuffer(tempm_source, tempm_stime);
				request.setAttribute(tempm_id + PageConstants.REMINDER_DATE,
						reminderDate.toString());
			}
		}

		request.setAttribute(HOTTEST_MSGS + days, hottestMessages);

	}

	@SuppressWarnings("rawtypes")
	private void getUserActivityDegree(HttpServletRequest request, int days) {
		MessageService msgService = new MessageService();
		List degrees = msgService.findRecentActiveUsers(days, 0, 10);
		request.setAttribute("degrees" + days, degrees);
	}

	@SuppressWarnings("rawtypes")
	private void getUserBehaviours(HttpServletRequest request) {
		UserService userService = new UserService();
 
		FavouriteService favouriteService = new FavouriteService();
		List favourites = null;

		FocusService focusService = new FocusService();

		List<Focus> focuses = focusService.findFocuses(0, 10);
		for (Iterator<Focus> iter = focuses.iterator(); iter.hasNext();) {
			Focus focus = iter.next();
			String fromUserAvatar = (String) request.getAttribute(focus
					.getFromUser() + PageConstants.AVATAR_POSTFIX);
			if (fromUserAvatar == null) {
				User fromUser = userService.findByUserName(focus.getFromUser());
				if (fromUser != null)
					request.setAttribute(focus.getFromUser()
							+ PageConstants.AVATAR_POSTFIX,
							fromUser.getAvatar());

			}
			String toUserAvatar = (String) request.getAttribute(focus
					.getToUser() + PageConstants.AVATAR_POSTFIX);
			if (toUserAvatar == null) {
				User toUser = userService.findByUserName(focus.getToUser());
				if (toUser != null)
					request.setAttribute(focus.getToUser()
							+ PageConstants.AVATAR_POSTFIX, toUser.getAvatar());
			}
		}
		MemberService memberService = new MemberService();
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);

		List memberGroups = null;
		if (Messages.LANG_LOCAL.equals(lang)) {
			memberGroups = memberService.findLocalMemberGroups(2, 0, 10);
			favourites = favouriteService.findLocalFavourites(0, 10);

		} else if (Messages.LANG_EN.equals(lang)) {

			memberGroups = memberService.findEnglishMemberGroups(2, 0, 10);
			favourites = favouriteService.findEnglishFavourites(0, 10);

		} else if (request.getLocale().getLanguage()
				.equals(Config.getProperty(Config.LOCAL_LANG))) {
			memberGroups = memberService.findLocalMemberGroups(2, 0, 10);
			favourites = favouriteService.findLocalFavourites(0, 10);

		} else {
			memberGroups = memberService.findEnglishMemberGroups(2, 0, 10);
			favourites = favouriteService.findEnglishFavourites(0, 10);

		}

		
		request.setAttribute("memberGroups", memberGroups);
		request.setAttribute("favourites", favourites);
		request.setAttribute("focuses", focuses);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
